import React from 'react';
import { Button, Drawer, Empty, Layout, Tree } from 'antd';
import { Form } from '@ant-design/compatible';
import { connect } from 'dva';
import {PageHeaderLayout, StandardTable, PageCard, IconButton} from '../../components';
import { modalWidth, pageSize } from '../../../config';

const reqApi = 'recommend';
const { Sider, Content } = Layout;
const { TreeNode } = Tree;
const mappingRank = ' ①②③④⑤⑥⑦⑧⑨⑩';

class page extends React.Component {
  state = {
    currentNavi: [],
    currentTitle: '全部',
    loading: false,
    loadingNavi: false,
    visibleNavi: false, // 教师列表显隐
    pagination: {
      current: 1,
      pageSize,
      onShowSizeChange: (_, size) => {
        const { pagination } = this.state;
        pagination.pageSize = size;
      },
    },
    exporting: false,
    teacherExporting: false, // 是否正在导出教师名单
  };

  componentDidMount() {
    this.funcGetNaviData();
    this.funcGetTeacherData();
  }

  // 获取菜单数据
  funcGetNaviData = () => {
    const { props } = this;
    props.dispatch({
      type: reqApi + '/listSpecial',
      payload: {},
    }).then(this.funcGetListData);
  };

  // 获取教师数据
  funcGetTeacherData = () => {
    this.setState({ loadingNavi: true });

    const { props } = this;
    props.dispatch({
      type: reqApi + '/listTeacher',
      payload: {},
    }).then(() => this.setState({ loadingNavi: false }));
  };

  // 获取列表数据
  funcGetListData = () => {
    this.setState({ loading: true });

    const { state } = this;
    const { pagination } = state;
    const { current, pageSize } = pagination;
    const { dispatch } = this.props;
    const payload = {
      currentPage: current,
      pageSize,
    };

    if (state.currentNavi.length) {
      payload.recommend = state.currentNavi.toString();
    }

    dispatch({
      type: reqApi + '/list',
      payload,
    }).then(() => this.setState({ loading: false }));
  };

  // 导航菜单
  naviMenu = () => {
    const { props } = this;
    const { teacherData } = props[reqApi];

    if (teacherData.length) {
      return (
        <div
          style={{
            maxHeight: 'calc(100vh - ' + (window.isMobile ? 56 : 120) + 'px)',
            overflow: 'auto',
          }}
        >
          <Tree
            blockNode
            defaultExpandAll
            onSelect={(selectedKeys, { selectedNodes }) => {
              const { key, title } = selectedNodes.length ? selectedNodes[0] : {};
              this.setState({
                currentNavi: key || selectedKeys,
                currentTitle: title || '全部',
                visibleNavi: false,
              }, this.funcGetListData);
            }}
          >
            {teacherData.map(({ key, title, count, rank }) => (
              <TreeNode
                key={key}
                title={(mappingRank[rank] || '') + ' ' + title + (count ? '：' + count + '人' : '')}
              />
            ))}
          </Tree>
        </div>
      );
    } else return <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />;
  };

  // 表格列
  columns = () => [
    {
      title: '推荐教师',
      dataIndex: 'recommend',
      width: 100,
    },
    {
      title: '学生姓名',
      dataIndex: 'name',
      width: 100,
    },
    {
      title: '性别',
      dataIndex: 'sex',
      width: 50,
      render: text => text === '1' ? '男' : '女',
    },
    {
      title: '联系电话',
      dataIndex: 'phone',
      width: 120,
    },
    {
      title: "身份证号",
      dataIndex: "idCardNum",
      width: 180,
    },
    {
      title: '是否住校',
      dataIndex: 'lodging',
      width: 80,
      render: text => text === '1' ? '住校' : '不住校',
    },
    {
      title: '报考专业',
      dataIndex: 'specialName',
    },
  ];

  // 内容列表
  contentTable = () => {
    const { state, props } = this;
    const { data, teacherData, counts } = props[reqApi];
    const { total, recommend1, recommend0 } = counts;
    const footerData = [];
    if (total !== recommend1 && total !== recommend0) {
      footerData.push('学生总数：' + total + '人');
    }
    if (recommend1) {
      footerData.push('经老师推荐：' + recommend1 + '人');
    }
    if (recommend0) {
      footerData.push('未经老师推荐：' + recommend0 + '人');
    }
    const footer = footerData.toString().replace(/,/g, '，');

    return (
      <div>
        <Button.Group>
          {window.isMobile ? (
            <Button
              type='primary'
              style={{ marginBottom: 16 }}
              onClick={() => this.setState({ visibleNavi: true })}
            >选择教师</Button>
          ) : null}

          <IconButton
            text='导出'
            type={window.isMobile ? 'default' : 'primary'}
            loading={state.exporting}
            disabled={state.exporting || !total}
            onClick={this.funcExport}
            style={{marginBottom: 16}}
          />

          <IconButton
              text='导出教师名单'
              type='default'
              loading={state.teacherExporting}
              disabled={state.teacherExporting || !teacherData.length}
              onClick={this.funcExportTeacher}
              style={{marginBottom: 16}}
          />
        </Button.Group>

        <StandardTable
          loading={state.loading}
          columns={this.columns()}
          data={{
            list: data,
            pagination: { ...state.pagination, total },
          }}
          onChange={(pageParams) => {
            const { pagination } = this.state;
            pagination.current = pageParams.current;
            this.funcGetListData();
          }}
          scrollX={1280}
          fixedNum
          footer={footer}
        />
      </div>
    );
  };

  // 导出
  funcExport = () => {
    this.setState({ exporting: true });

    const { state } = this;
    const { dispatch } = this.props;
    const payload = {
      currentPage: 1,
      pageSize: 10000,
    };

    if (state.currentNavi.length) {
      payload.recommend = state.currentNavi.toString();
    }

    dispatch({
      type: reqApi + '/listExport',
      payload,
    }).then(() => {
      this.setState({ exporting: false });

      const { props } = this;
      const { exportData, counts } = props[reqApi];
      localStorage.setItem('studentData', JSON.stringify(exportData));
      localStorage.setItem('studentCounts', JSON.stringify(counts));
      localStorage.setItem('studentTitle', state.currentTitle);

      const w = window.innerWidth, h = window.innerHeight;
      const win = window.open(
        'exportRecommend.html',
        '_blank',
        'width=' + w + ',height=' + h + ',location=0,menubar=0,status=0,toolbar=0,scrollbars=1'
      );
      win.focus();
    });
  };

  // 导出教师名单
  funcExportTeacher = () => {
    this.setState({ teacherExporting: true });

    const { props } = this;
    const { teacherData, counts } = props[reqApi];
    localStorage.setItem('teacherData', JSON.stringify(teacherData));
    localStorage.setItem('studentCounts', JSON.stringify(counts));

    this.setState({ teacherExporting: false });

    const w = window.innerWidth, h = window.innerHeight;
    const win = window.open(
      'exportTeacher.html',
      '_blank',
      'width=' + w + ',height=' + h + ',location=0,menubar=0,status=0,toolbar=0,scrollbars=1'
    );
    win.focus();
  };

  render() {
    const { state, props } = this;

    return (
      <PageHeaderLayout title={props.route.name}>
        <PageCard
          bodyStyle={{ padding: 0, overflow: 'hidden' }}
          children={(
            <Layout>
              {window.isMobile ? null : (
                <Sider theme='light' style={{ borderRight: '1px solid gainsboro' }}>
                  {this.naviMenu()}
                </Sider>
              )}
              <Content style={{ padding: '16px 8px 0 8px', backgroundColor: 'white' }}>
                {this.contentTable()}
              </Content>
            </Layout>
          )}
        />

        <Drawer
          width={window.isMobile ? window.innerWidth : modalWidth}
          title='选择教师'
          visible={state.visibleNavi}
          onClose={() => this.setState({ visibleNavi: false })}
          bodyStyle={{ padding: 0 }}
        >
          {this.naviMenu()}
        </Drawer>

      </PageHeaderLayout>
    );
  }
}

const page2 = Form.create()(page);
export default connect(({ recommend, menu }) => ({ recommend, menu }))(page2);
